package cn.wolfcde.luowowo.website.util;

import cn.wolfcde.luowowo.website.key.CookieKey;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static void addCookie(String token, HttpServletResponse response) {

        if(token != null && ""!= token){

            Cookie cookie = new Cookie(CookieKey.LOGIN_TOKEN.getName(),token);

            cookie.setMaxAge(CookieKey.LOGIN_TOKEN.getLivingTime().intValue());

            cookie.setPath("/");

            response.addCookie(cookie);

        }

    }

     public static String getToken(HttpServletRequest request, HttpServletResponse response) {

         Cookie[] cookies = request.getCookies();

         if(cookies != null){

             for (Cookie cookie : cookies) {

                 if(cookie.getName().equals(CookieKey.LOGIN_TOKEN.getName())){

                     cookie.setMaxAge(CookieKey.LOGIN_TOKEN.getLivingTime().intValue());

                     //必须加上路径
                     cookie.setPath("/");

                     response.addCookie(cookie);

                     return cookie.getValue();

                 }

             }
         }
         return null;
     }



    /**
     * 获取cookie
     * @param request
     * @param cookieName
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(cookieName)){
                    return cookie;
                }
            }
        }
        return null;
    }
}
